<template>
<div class="com-container">
		<div class="title" :style="comStyle">
			<span style="cursor: default">{{ '▎' + state.showTitle }}</span>
			<span
				@click="qh"
				class="iconfont title-icon icon-arrow-down"
				:style="comStyle"
			></span>
			<div class="select-icon" v-show="state.showChoice" :style="marginStyle">
				<div
					@click="handleSelect(item.key, item.text)"
					class="select-item"
					v-for="item in selectType"
					:key="item.key"
				>
					{{ item.text }}
				</div>
			</div>
		</div>
	<div class="com-chart" ref="treadRef" id="treadRef"></div>
</div>
</template>
<script lang='ts' setup>
import { ref, reactive, onMounted, onUnmounted, computed, watch } from 'vue';
import {isValidKey} from '../type/utils'
import * as echarts from 'echarts'
import socketService from '../api/socket_sever'
import '../../public/theme/chalk'
import '../../public/theme/vintage'
import {gettrend} from '../api/api'
import { useStore } from 'vuex';
import { getThemeValue } from '@/utils/theme_utils';
const store = useStore()
const treadRef = ref()
	const state = reactive<{
    // myChart: echarts.ECharts | null,
    data: API.Welcome
    setinter: number
    showChoice: boolean
    showTitle: string,
    selectType?: {
      key: string
      text: string
    }[],
    titleFontSize:number
    choiceType:string
	}>({
    // myChart: null,
    data: {},// 服务器返回数据
    setinter: 0,
    showChoice: false,
    showTitle: '地区销量趋势',
    selectType: [],
    titleFontSize: 0,
    choiceType: 'map'
	})
  // 设置给标题的样式
  const comStyle = computed( () => {
				return {
					fontSize: state.titleFontSize + 'px',
					color: getThemeValue(store.state.theme).titleColor
				};
  })
    const marginStyle = computed( () => {
				return {
					marginLeft: state.titleFontSize + 'px',
          'backgroundColor': store.state.color,
          'titleColor': store.state.color,
				};
  })
  let myChart: echarts.ECharts | null = null
	onMounted(async() => {
      await initexs()
      screenAdapter()
      window.addEventListener('resize',screenAdapter )
	})
  onUnmounted(() => {
    clearInterval(state.setinter)
    socketService.Instance.unRegisterCallBack('trend')
    window.removeEventListener('resize', screenAdapter)
  })
  // 初始化exs
  const initexs = async() => {
    var chartDom = document.getElementById('treadRef');
    myChart = echarts.init(chartDom as HTMLElement, store.state.theme)
    const initoption = {
      title: {
        left: 20,
        top: 20
      },
      xAxis: {
        type: 'category',
        boundaryGap: false
      },
      yAxis: {
        type: 'value',
        boundaryGap: false
      },
      tooltip: {
				trigger: 'axis',
				axisPointer: {
					type: 'none'
				}
			},
      legend: {
        left: 20,
        top: '15%',
        icon: 'circle'
      },
      grid: {
        top: '25%',
        left: '3%',
        right: '6%',
        bottom: '3%',
        containLabel: true
      },
    }
    initoption && (myChart as  echarts.ECharts).setOption(initoption);
    socketService.Instance.registerCallBack('trend', getData)
    try {
      await gettrend()
    } catch (error) {
      console.log(error);
    }
  }
    // 获取数据
  const getData = (data: API.Welcome) => {
    state.data = data
    updataChar()
  }
  const selectType = computed(() => {
				if (!state.data) {
					return [];
				} else {
					return state.data.type?.filter(item => {
						return item.key !== state.choiceType
					});
				}
			})
    // 更新图表
  const updataChar = () => {
    const time = state.data.common?.month
    let value
    if (!isValidKey(state.choiceType, state.data)) { // 先进行判断，之后就不会报错了
      throw Error('invalid sequence');
    } else {
       value = state.data[state.choiceType]['data']
    }
// 半透明的颜色值
				const colorArr1 = [
					'rgba(11, 168, 44, 0.5)',
					'rgba(44, 110, 255, 0.5)',
					'rgba(22, 242, 217, 0.5)',
					'rgba(254, 33, 30, 0.5)',
					'rgba(250, 105, 0, 0.5)'
				];
				// 全透明的颜色值
				const colorArr2 = [
					'rgba(11, 168, 44, 0)',
					'rgba(44, 110, 255, 0)',
					'rgba(22, 242, 217, 0)',
					'rgba(254, 33, 30, 0)',
					'rgba(250, 105, 0, 0)'
				];
    const seriesarr = (value as {name: string, data: []}[]).map((item, index) => {
      return {
        name: item.name,
        stack: 'map',
        type: 'line',
        data: item.data,
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0,0,0,1,[
            {
              color: colorArr1[index],
              offset: 0 
            },
            {
              color: colorArr2[index],
              offset: 1
            }
          ])
        }
      }
    })
    const legendarr = (value as {name: string, data: []}[]).map((item) => {
      return item.name
    })
    const dataoption = {
      legend: {
        data: legendarr,
      },
      xAxis: {
        data: time
      },
      series: seriesarr
    }
    dataoption && (myChart as  echarts.ECharts).setOption(dataoption);
  }
  const screenAdapter = () => {
    state.titleFontSize = treadRef.value.offsetWidth / 100 * 3.6;
    // console.log(titleFontSize);
    const Adapteroption = {
      legend: {
        itemWidth: state.titleFontSize / 1.5,
        itemHeight: state.titleFontSize / 1.5,
        itemGap:  state.titleFontSize,
        textStyle: {
          fontSize: state.titleFontSize / 3
        }
      },
      series: [{
        barWidth: state.titleFontSize,
      }]
    }
    Adapteroption && (myChart as  echarts.ECharts).setOption(Adapteroption);
    (myChart as  echarts.ECharts).resize()
  }
  const handleSelect = (currentValue:string, text:string) => {
				state.choiceType = currentValue;
        state.showTitle = text
				updataChar();
				state.showChoice = false;
			}
      const qh = () => {
        state.showChoice = !state.showChoice
      }
      defineExpose({
        screenAdapter
      })
      watch ( () => store.state.theme, async() => {
        // console.log('qweqwe');
        (myChart as echarts.ECharts).dispose();
        await initexs()
        screenAdapter()
        updataChar()
      }, {
        // immediate: true, // 是否初始化立即执行一次, 默认是false
        deep: true // 是否是深度监视, 默认是false
      })
</script>
<style lang='less' scoped>
.title {
	position: absolute;
	left: 20px;
	top: 20px;
	z-index: 10;
	color: white;

	.title-icon {
		margin-left: 10px;
		cursor: pointer;
	}

	.select-item {
		cursor: pointer;
	}
}
</style>